import {createRouter, createWebHistory} from 'vue-router'
import HelloWorld from "../components/HelloWorld.vue";
import ThemeDemo from "../views/ThemeDemo.vue";
import UserLoginPage from "../pages/UserLoginPage.vue";
import BasicLayout from "../layout/BasicLayout.vue";
import VisualPage from "../pages/VisualPage.vue"
import PictureManagePage from "../pages/PictureManagePage/PictureManagePage.vue";
import UserManagePage from "../pages/UserManagePage.vue";
import {useUserStore} from "../stores/useUserStore";
import {Message} from "@arco-design/web-vue";
import UserCenterPage from "../pages/UserCenterPage.vue";

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: [
        {
            path: "/login",
            name: "Login",
            component: UserLoginPage
        },
        {
            path: "/",
            name: "Layout",
            component: BasicLayout,
            meta: {
                role: "admin",
                login: true
            },
            children: [
                {
                    path: "",
                    name: "Home",
                    component: VisualPage
                },
                {
                    path: "/user",
                    component: UserManagePage,
                },
                {
                    path: "/picture",
                    component: PictureManagePage
                },
                {
                    path: "/center",
                    component: UserCenterPage
                },
                {
                    path: "/hello",
                    name: "hello",
                    component: HelloWorld
                },
                {
                    path: "/theme",
                    name: "theme",
                    component: ThemeDemo
                }
            ]
        }
    ]
})

// 不在这里初始化store
// const userStore = useUserStore()

// 添加全局前置守卫，在每次路由切换前重置滚动条位置
router.beforeEach((to, from, next) => {

    const routeMeta = to.meta;
    if (routeMeta.login){
        // 在路由守卫内部才调用useUserStore
        const userStore = useUserStore();
        if (!userStore.isLogin()) {
            // 将当前要访问的路径作为查询参数，登录后可以重定向回来
            return next({ path: "/login", query: { redirect: to.fullPath } });
        }

        if (routeMeta.role!==userStore.getLoginUser()?.role){
            Message.error("权限不足")
            return
        }
    }
    // 继续路由导航
    next();
})

export default router